class Solution {
    public int[] relativeSortArray(int[] arr1, int[] arr2) {
        int[] counter = new int[1001];
        int[] ans = new int[arr1.length];
        int idx = 0;
        for (int i = 0; i < arr1.length; i++) {
            counter[arr1[i]]++;
        }
        for (int i = 0; i < arr2.length; i++) {
            while (counter[arr2[i]] > 0) {
                ans[idx++] = arr2[i];
                counter[arr2[i]]--;
            }
        }
        for (int i = 0; i < counter.length; i++) {
            while (counter[i] > 0) {
                ans[idx++] = i;
                counter[i]--;
            }
        }
        return ans;
    }
}
